
from driver import get_logger
from driver import device_manager, JsonObject, load_mapping_from_file, DataType
from driver.device import OpcuaPlcDevice


logger = get_logger("driverServer")

class OPCUAPlcServer(object):
    """OPCUA PLC服务类"""
    def __init__(self):
        try:
            self.device:OpcuaPlcDevice = device_manager.get_device("opcua_test_client")
            self.device.initialize()
            self.device.connect()
            self.device.monitor_heartbeat(1.0,self.connStateCallback)
            #获取地址映射，根据地址文件指定的地址(可根据真实设备地址修改地址映射文件)
            JsonObj:JsonObject = load_mapping_from_file("config/device_interface/opcuaplcdevice.json",return_type="object")

            self.registers = JsonObj.get("address_mapping").get("registers")
        except Exception as e:
            logger.error("OpcuaPlcServer init error:{error}".format(error=e))



    def connStateCallback(self,state):
        """连接状态回调函数"""
        try:
            print("state: ", state)
            logger.info("Connection state changed:{state}".format(state=state))
        except Exception as e:

            logger.error("Error in connStateCallback:{error}".format(error=e))

    # 实时定义数据
    def callback_data(self,data):
        """数据回调函数"""
        try:
            print("Received data:", data)
        except Exception as e:
            print("Error in callback_data:", e)


    def callback_device_state(self,data):
        """设备状态回调函数"""

        try:
            print("Received device_state:", data)
        except Exception as e:
            print("Error in callback_device_state:", e)


    def callback_alarm(self,data):
        """报警回调函数"""
        try:
            print("Received alarm:", data)
        except Exception as e:
            print("Error in callback_alarm:", e)

    def test_func(self):
        """测试函数"""
        logger.info("test_func")

        try:
            # 设置名称空间================================================
            self.device.set_namespaces(5,"i")
            # 读取数据
            read_single_data = self.device.read_single("300")
            print("read_single_data:", read_single_data)
            read_data = self.device.read("44")
            print("read_data:", read_data)
            read_batch_data = self.device.read_batch(["300","44"])
            print("read_batch_data:", read_batch_data)
            read_batch_data = self.device.read(["300","44"])
            print("read_batch_data:", read_batch_data)

            # 写入数据
            write_data = self.device.write_single("11",32)
            print("write_data:", write_data)
            write_data = self.device.communication.write_batch({"11":32,"12":33})
            print("write_data:", write_data)
            write_data = self.device.write_batch(["11","12"],[32,33])
            print("write_data:", write_data)

            write_data = self.device.write("44",123,DataType.FLOAT)
            print("write_data:", write_data)
            write_batch_data = self.device.write_batch(["70","44"],["hello world2",123],[DataType.STRING,DataType.FLOAT])
            print("write_batch_data:", write_batch_data)
            write_batch_data = self.device.write(["70","44"],["hello world2",123],[DataType.STRING,DataType.FLOAT])
            print("write_batch_data:", write_batch_data)
            write_batch_data = self.device.write([("70","hello world2",DataType.STRING),("44",123,DataType.FLOAT)])
            print("write_batch_data:", write_batch_data)

            #使用绝对地址======================================================
            # 读取数据
            read_single_data = self.device.read_single("ns=5;i=300")
            print("read_single_data:", read_single_data)
            read_data = self.device.read("ns=5;i=44")
            print("read_data:", read_data)
            read_batch_data = self.device.read_batch(["ns=5;i=300","ns=5;i=44"])
            print("read_batch_data:", read_batch_data)
            read_batch_data = self.device.read(["ns=5;i=300","ns=5;i=44"])
            print("read_batch_data:", read_batch_data)

            # 写入数据
            write_data = self.device.write_single("ns=5;i=11",32)
            print("write_data:", write_data)
            write_data = self.device.communication.write_batch({"ns=5;i=11":32,"ns=5;i=12":33})
            print("write_data:", write_data)
            write_data = self.device.write_batch(["ns=5;i=11","ns=5;i=12"],[32,33])
            print("write_data:", write_data)

            write_data = self.device.write("ns=5;i=44",123,DataType.FLOAT)
            print("write_data:", write_data)
            write_batch_data = self.device.write_batch(["ns=5;i=70","ns=5;i=44"],["hello world2",123],[DataType.STRING,DataType.FLOAT])
            print("write_batch_data:", write_batch_data)
            write_batch_data = self.device.write(["ns=5;i=70","ns=5;i=44"],["hello world2",123],[DataType.STRING,DataType.FLOAT])
            print("write_batch_data:", write_batch_data)
            write_batch_data = self.device.write([("ns=5;i=70","hello world2",DataType.STRING),("ns=5;i=44",123,DataType.FLOAT)])
            print("write_batch_data:", write_batch_data)

            #设备控制
            bool_start = self.device.start()
            print("bool_start:", bool_start)
            bool_stop = self.device.stop()
            print("bool_stop:", bool_stop)
            bool_pause = self.device.pause()
            print("bool_pause:", bool_pause)
            bool_resume = self.device.resume()
            print("bool_resume:", bool_resume)
            bool_reset = self.device.reset()
            print("bool_reset:", bool_reset)
            bool_emergency_stop = self.device.emergency_stop()
            print("bool_emergency_stop:", bool_emergency_stop)


            self.device.subscribe_tag("ns=4;i=34", self.callback_alarm)

            self.device.subscribe_tag("ns=4;i=33", self.callback_device_state)

            self.device.subscribe_tag("ns=4;i=16", self.callback_data)


            # 报警管理
            alarm_info = self.device.get_active_alarms()
            print("alarm_info:", alarm_info)
            alarm_ack = self.device.acknowledge_alarm(None)
            print("alarm_ack:", alarm_ack)
            alarm_clear = self.device.clear_alarm(None)
            print("alarm_clear:", alarm_clear)
            alarm_suppress = self.device.suppress_alarm(None)
            print("alarm_suppress:", alarm_suppress)

            # 安全功能
            bool_enable_safety = self.device.enable_safety()
            print("bool_enable_safety:", bool_enable_safety)
            bool_disable_safety = self.device.disable_safety()
            print("bool_disable_safety:", bool_disable_safety)
            bool_reset_safety = self.device.reset_safety()
            print("bool_reset_safety:", bool_reset_safety)
            bool_lock = self.device.lock_device(True)
            print("bool_lock:", bool_lock)


            # 系统管理
            bool_reboot = self.device.reboot()
            print("bool_reboot:", bool_reboot)
            bool_shutdown = self.device.shutdown()
            print("bool_shutdown:", bool_shutdown)



            # 添加检查确保registers不为None
            if self.registers is None:
                print("Error: Failed to load address mapping configuration")
                exit(1)

            read_data = self.device.read_batch(self.registers._start.node_id)
            print("read_data:", read_data)
            write_data = self.device.write_single(self.registers._start.node_id, True, self.registers._start.data_type)
            print("write_data:", write_data)


        except Exception as e:
            print(e)
